<?php

namespace App\Http\Controllers\Home\Wechat;

use Illuminate\Http\Request;

use App\Http\Requests;
//use App\Http\Controllers\Controller;
use App\Models\wechat\Ad;
use App\Models\shop\Product;
use App\Models\shop\goodscategory;

class ProductController extends CommonController
{
    public function __construct()
    {
//        parent::__construct();
        view()->share([
            '_category' => 'on'
        ]);
    }


    //显示商品列表(从获取到的category_id中，找出对应category_id的所有商品)
    //如果搜索，搜索完也显示商品列表
    public function index(Request $request)
    {
        $where=function($query) use ($request) {

            //通过搜索searchword匹配商品
            if($request->has('searchword') && $request->searchword != '')
            {
                $name='%'.$request->searchword.'%';
                $query->where('name','like',$name);
            }

            //点击分类的时候，传入category_id
            if($request->has('category_id') && $request->category_id != '')
            {
                $query->where('category_id',$request->category_id);
            }
        };

        $products=Product::where($where)->orderBy('is_top', "desc")
            ->orderBy('created_at')->get();
//        return $products;
        
        //如果输入的关键字搜索，没有查询到商品，默认返回推荐的商品！
        if(count($products)==0){
            echo '没有找到匹配的商品！为您推荐以下商品：';
            $products=Product::where('is_recommend',true)->get();
        }
        return view('home.wechat.products.list')->with('products',$products);
    }

    //显示商品栏目分类首页
    public function category()
    {
        $categories=goodscategory::get_categories();
//        return $categories;
        return view('home.wechat.products.category')->with('categories',$categories);
    }
    
    //显示单个商品信息
    public function show($id)
    {
        $product=Product::find($id);
//        return $product;

        //推荐商品 展示category_id相同的商品
        //当前分类,推荐商品. 由于商品太少,改为推荐所有分类的商品
        $recommends = Product::where('is_recommend', true)
//            ->where('category_id', $product->category_id)
            ->where('id', '<>', $id)  //排除本身这个商品
            ->orderBy('is_top', 'desc')
            ->get();

        return view('home.wechat.products.show')->with('product',$product)->with('recommends',$recommends);
    }


    //显示搜索
    public function search()
    {
        //在搜索页显示推荐商品
        $products=Product::where('is_recommend',true)
            ->orderBy('is_top', "desc")
            ->orderBy('created_at')
            ->get();

        return view('home.wechat.products.search')->with('products',$products);
    }
    
}
